﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using DesertedRoadStudios.BlogNetNuke.Components;
using DotNetNuke.HttpModules.Config;

namespace DesertedRoadStudios.BlogNetNuke
{
    public partial class Settings : ModuleSettingsBase
    {
        // Basic Configuration
        TextBox tbMaxPosts;
        CheckBox cbUsePageExtensions;
        TextBox tbPageExtension;

        // TinyURLs
        CheckBox cbUseShortenedURL;
        TextBox tbDomainName;
        CheckBox cbLogRedirects;

        // Layout
        RadioButtonList rblBlogViewContainer;
        DropDownList ddlBlogViewContainer;
        RadioButtonList rblPostsListContainer;
        DropDownList ddlPostsListContainer;
        RadioButtonList rblPostsViewContainer;
        DropDownList ddlPostsViewContainer;

        // Comments
        RadioButtonList rblCommentsViewContainer;
        DropDownList ddlCommentsViewContainer;
        RadioButtonList rblCommentsFormContainer;
        DropDownList ddlCommentsFormContainer;

        protected void Page_Init(object sender, EventArgs e)
        {
            // Basic Configuration
            tbMaxPosts = FindControl("tbMaxPosts") as TextBox;
            cbUsePageExtensions = FindControl("cbUsePageExtensions") as CheckBox;
            tbPageExtension = FindControl("tbPageExtension") as TextBox;

            // TinyURLs
            cbUseShortenedURL = FindControl("cbUseShortenedURL") as CheckBox;
            tbDomainName = FindControl("tbDomainName") as TextBox;
            cbLogRedirects = FindControl("cbLogRedirects") as CheckBox;

            // Layout
            rblBlogViewContainer = FindControl("rblBlogViewContainer") as RadioButtonList;
            ddlBlogViewContainer = FindControl("ddlBlogViewContainer") as DropDownList;
            rblPostsListContainer = FindControl("rblPostsListContainer") as RadioButtonList;
            ddlPostsListContainer = FindControl("ddlPostsListContainer") as DropDownList;
            rblPostsViewContainer = FindControl("rblPostsViewContainer") as RadioButtonList;
            ddlPostsViewContainer = FindControl("ddlPostsViewContainer") as DropDownList;

            // Comments
            rblCommentsViewContainer = FindControl("rblCommentsViewContainer") as RadioButtonList;
            ddlCommentsViewContainer = FindControl("ddlCommentsViewContainer") as DropDownList;
            rblCommentsFormContainer = FindControl("rblCommentsFormContainer") as RadioButtonList;
            ddlCommentsFormContainer = FindControl("ddlCommentsFormContainer") as DropDownList;
        }

        public override void LoadSettings()
        {
            BlogNetNukeController bnn = new BlogNetNukeController();
            Dictionary<string, string> settings = bnn.GetSettings(PortalId, ModuleId);

            if (settings.ContainsKey("PostsPerPage") && !string.IsNullOrEmpty(settings["PostsPerPage"]))
                tbMaxPosts.Text = settings["PostsPerPage"];

            if (settings.ContainsKey("UsePageExtensions") && !string.IsNullOrEmpty(settings["UsePageExtensions"]))
                cbUsePageExtensions.Checked = Convert.ToBoolean(settings["UsePageExtensions"]);

            if (settings.ContainsKey("PageExtension") && !string.IsNullOrEmpty(settings["PageExtension"]))
                tbPageExtension.Text = settings["PageExtension"];

            if (settings.ContainsKey("UseShortenedURL") && !string.IsNullOrEmpty(settings["UseShortenedURL"]))
                cbUseShortenedURL.Checked = Convert.ToBoolean(settings["UseShortenedURL"]);

            if (settings.ContainsKey("TinyURL") && !string.IsNullOrEmpty(settings["TinyURL"]))
                tbDomainName.Text = settings["TinyURL"];

            if (settings.ContainsKey("LogRedirects") && !string.IsNullOrEmpty(settings["LogRedirects"]))
                cbLogRedirects.Checked = Convert.ToBoolean(settings["LogRedirects"]);

            if (settings.ContainsKey("BlogViewContainerLocation") && !string.IsNullOrEmpty(settings["BlogViewContainerLocation"]) &&
                settings.ContainsKey("BlogViewContainerControl") && !string.IsNullOrEmpty(settings["BlogViewContainerControl"]))
            {
                rblBlogViewContainer.SelectedValue = settings["BlogViewContainerLocation"];
                rblGeneric_SelectedIndexChanged(rblBlogViewContainer, null);

                if (ddlBlogViewContainer.Items.FindByValue(settings["BlogViewContainerControl"].Substring(1)) != null)
                    ddlBlogViewContainer.SelectedValue = settings["BlogViewContainerControl"].Substring(1);
            }
            else
            {
                rblBlogViewContainer.SelectedValue = "Samples";
                rblGeneric_SelectedIndexChanged(rblBlogViewContainer, null);
            }

            if (settings.ContainsKey("PostsListContainerLocation") && !string.IsNullOrEmpty(settings["PostsListContainerLocation"]) &&
                settings.ContainsKey("PostsListContainerControl") && !string.IsNullOrEmpty(settings["PostsListContainerControl"]))
            {
                rblPostsListContainer.SelectedValue = settings["PostsListContainerLocation"];
                rblGeneric_SelectedIndexChanged(rblPostsListContainer, null);

                if (ddlPostsListContainer.Items.FindByValue(settings["PostsListContainerControl"].Substring(1)) != null)
                    ddlPostsListContainer.SelectedValue = settings["PostsListContainerControl"].Substring(1);
            }
            else
            {
                rblPostsListContainer.SelectedValue = "Samples";
                rblGeneric_SelectedIndexChanged(rblPostsListContainer, null);
            }

            if (settings.ContainsKey("PostsViewContainerLocation") && !string.IsNullOrEmpty(settings["PostsViewContainerLocation"]) &&
                settings.ContainsKey("PostsViewContainerControl") && !string.IsNullOrEmpty(settings["PostsViewContainerControl"]))
            {
                rblPostsViewContainer.SelectedValue = settings["PostsViewContainerLocation"];
                rblGeneric_SelectedIndexChanged(rblPostsViewContainer, null);

                if (ddlPostsViewContainer.Items.FindByValue(settings["PostsViewContainerControl"].Substring(1)) != null)
                    ddlPostsViewContainer.SelectedValue = settings["PostsViewContainerControl"].Substring(1);
            }
            else
            {
                rblPostsViewContainer.SelectedValue = "Samples";
                rblGeneric_SelectedIndexChanged(rblPostsViewContainer, null);
            }

            if (settings.ContainsKey("CommentsViewContainerLocation") && !string.IsNullOrEmpty(settings["CommentsViewContainerLocation"]) &&
                settings.ContainsKey("CommentsViewContainerControl") && !string.IsNullOrEmpty(settings["CommentsViewContainerControl"]))
            {
                rblCommentsViewContainer.SelectedValue = settings["CommentsViewContainerLocation"];
                rblGeneric_SelectedIndexChanged(rblCommentsViewContainer, null);

                if (ddlCommentsViewContainer.Items.FindByValue(settings["CommentsViewContainerControl"].Substring(1)) != null)
                    ddlCommentsViewContainer.SelectedValue = settings["CommentsViewContainerControl"].Substring(1);
            }
            else
            {
                rblCommentsViewContainer.SelectedValue = "Samples";
                rblGeneric_SelectedIndexChanged(rblCommentsViewContainer, null);
            }

            if (settings.ContainsKey("CommentsFormContainerLocation") && !string.IsNullOrEmpty(settings["CommentsFormContainerLocation"]) &&
                settings.ContainsKey("CommentsFormContainerControl") && !string.IsNullOrEmpty(settings["CommentsFormContainerControl"]))
            {
                rblCommentsFormContainer.SelectedValue = settings["CommentsFormContainerLocation"];
                rblGeneric_SelectedIndexChanged(rblCommentsFormContainer, null);

                if (ddlCommentsFormContainer.Items.FindByValue(settings["CommentsFormContainerControl"].Substring(1)) != null)
                    ddlCommentsFormContainer.SelectedValue = settings["CommentsFormContainerControl"].Substring(1);
            }
            else
            {
                rblCommentsFormContainer.SelectedValue = "Samples";
                rblGeneric_SelectedIndexChanged(rblCommentsFormContainer, null);
            }

        }

        protected void rblGeneric_SelectedIndexChanged(object sender, EventArgs e)
        {
            RadioButtonList rbl = sender as RadioButtonList;
            DropDownList ddl = FindControl("ddl" + rbl.ID.Substring(3)) as DropDownList;

            string[] files = { };
            string dirPrefix = string.Empty;
            string dirName = string.Empty;

            if (rbl.SelectedValue.Equals("Samples"))
                dirPrefix = MapPath("~/DesktopModules/BlogNetNuke/Containers");
            else if (rbl.SelectedValue.Equals("Host"))
                dirPrefix = MapPath("~/Portals/_default/Containers");
            else if (rbl.SelectedValue.Equals("Site"))
                dirPrefix = PortalSettings.HomeDirectoryMapPath + "Containers";

            ddl.Items.Clear();

            try
            {
                files = Directory.GetFiles(dirPrefix, "*.ascx", SearchOption.AllDirectories);

                FileInfo fInfo;
                foreach (string file in files)
                {
                    fInfo = new FileInfo(file);
                    dirName = fInfo.FullName.Substring(dirPrefix.Length);
                    ddl.Items.Add(new ListItem(dirName.Substring(1, dirName.Length - 1 - fInfo.Extension.Length).Replace("\\", " - "), fInfo.FullName.Substring(MapPath("~").Length - 1).Replace("\\", "/")));
                }
            }
            catch { }
        }

        public override void UpdateSettings()
        {
            BlogNetNukeController bnn = new BlogNetNukeController();
            bnn.SetSetting(PortalId, ModuleId, "PostsPerPage", tbMaxPosts.Text);
            bnn.SetSetting(PortalId, ModuleId, "UsePageExtensions", cbUsePageExtensions.Checked.ToString());
            bnn.SetSetting(PortalId, ModuleId, "PageExtension", tbPageExtension.Text);
            bnn.SetSetting(PortalId, ModuleId, "UseShortenedURL", cbUseShortenedURL.Checked.ToString());
            bnn.SetSetting(PortalId, ModuleId, "TinyURL", tbDomainName.Text);
            bnn.SetSetting(PortalId, ModuleId, "LogRedirects", cbLogRedirects.Checked.ToString());
            bnn.SetSetting(PortalId, ModuleId, "BlogViewContainerLocation", rblBlogViewContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "BlogViewContainerControl", "~" + ddlBlogViewContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "PostsListContainerLocation", rblPostsListContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "PostsListContainerControl", "~" + ddlPostsListContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "PostsViewContainerLocation", rblPostsViewContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "PostsViewContainerControl", "~" + ddlPostsViewContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "CommentsViewContainerLocation", rblCommentsViewContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "CommentsViewContainerControl", "~" + ddlCommentsViewContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "CommentsFormContainerLocation", rblCommentsFormContainer.SelectedValue);
            bnn.SetSetting(PortalId, ModuleId, "CommentsFormContainerControl", "~" + ddlCommentsFormContainer.SelectedValue);

            if ((cbUseShortenedURL.Checked) && (!string.IsNullOrEmpty(tbDomainName.Text)))
            {
                // Check either if portal alias does not exists or is already set to current portal (i.e. don't set alias if assigned to a different portal)
                DotNetNuke.Entities.Portals.PortalAliasInfo pai = DotNetNuke.Entities.Portals.PortalAliasController.GetPortalAliasInfo(tbDomainName.Text.ToLower());
                if ((pai == null) || (pai.PortalID == PortalId))
                {
                    // If portal alias is null (i.e. has not been already assigned to this portal)
                    if (pai == null)
                    {
                        DotNetNuke.Entities.Portals.PortalAliasController pac = new DotNetNuke.Entities.Portals.PortalAliasController();
                        pai = new DotNetNuke.Entities.Portals.PortalAliasInfo();
                        pai.PortalID = PortalId;
                        pai.HTTPAlias = tbDomainName.Text.ToLower();
                        pac.AddPortalAlias(pai);
                    }
                    bnn.AddTinyUrl(tbDomainName.Text, ModuleId, cbLogRedirects.Checked);

                    // Save ReWrite Rule
                    RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
                    RewriterRule rule = new RewriterRule();
                    rule.LookFor = "^https?://" + tbDomainName.Text + "/(.*){8,8}";
                    rule.SendTo = "~/BNNDefault.aspx";

                    bool found = false;
                    for (int i = 0; i < rules.Count; i++)
                    {
                        if (rules[i].LookFor.Equals(rule.LookFor, StringComparison.InvariantCultureIgnoreCase))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        rules.Add(rule);
                        RewriterConfiguration.SaveConfig(rules);
                    }
                }
            }
        }

    }
}
